from datetime import datetime
from typing import Union

import jwt
from aioredis import Redis
from sqlalchemy.exc import SQLAlchemyError

from api.router.model.user_model import User
from config import appSettings
from lib import utils
from lib.wx import auth

from api.src.db import repositories, schemas


def token_refresh(user: User):
    # 获取用户信息续期
    # user_info = repositories.get_user(db, user.user_id)
    user.iat = int(datetime.now().timestamp())
    user.exp = int(datetime.now().timestamp() + appSettings.jwt_expired * 60)
    print(user.model_dump())
    author = jwt.encode(
        user.model_dump(),
        appSettings.jwt_secret_key,
        algorithm=appSettings.jwt_algorithm,
    )
    return author


class UsersService:
    def __init__(self, cache: Redis = None):
        self.cache = cache
        pass

    # 微信用户登录
    def wx_user_login(
        self,
        js_code: str,
        invite_code: str = "",
        nick_name: str = "微信用户",
        avatar: str = "",
    ):
        # 校验js_code 有效性
        wx_login_res, errcode = auth.wx_login(js_code)
        if errcode:
            return None, wx_login_res
        # 获取用户信息
        user = repositories.get_user_by_open_id(wx_login_res["openid"])
        # 用户信息同步
        if not user:
            # 注册
            print(invite_code, avatar)
            create_user = schemas.UserCreate(
                wx_js_code=js_code,
                wx_open_id=wx_login_res["openid"],
                wx_session_key=wx_login_res["session_key"],
                nick_name=nick_name,
                avatar=avatar,
                wx_union_id="",
                invite_code=invite_code,
                up_time=int(datetime.now().timestamp()),
            )
            create_interest = schemas.InterestCreate(
                user_id=0, is_viper=0, points=0, free_count=0, status=0
            )
            invitation = None
            if invite_code is not None:
                # 绑定邀请关系
                invitation = schemas.InvitationCreate(
                    inviter_id=utils.get_id(invite_code)
                )
            try:
                user = repositories.create_user(
                    create_user, create_interest, invitation
                )
            except SQLAlchemyError as e:
                return None, e

        # 更新邀请码
        if user.invite_code is None:
            invite_code = utils.activation_code(user.id)
            repositories.update_user_invite_code(user.id, invite_code)
            user.invite_code = invite_code
        return user, None

    def profile(self, user_id: int):
        user_info = repositories.get_user(user_id)
        return user_info

    def order_list(self, user_id: int, page: int = 1, page_size: int = 10):
        order_list = repositories.get_order_list(user_id, page, page_size)
        return order_list

    def create_order(self, user_id: int, pic: str, size: str, pixel: str, type: int):
        create_order = schemas.OrderCreate(
            user_id=user_id,
            pic=pic,
            size=size,
            pixel=pixel,
            type=type,
            status=0,
            up_time=int(datetime.now().timestamp()),
        )
        order = repositories.create_order(create_order)
        return order

    def order_detail(self, user_id: int, order_id: int):
        order = repositories.get_order(user_id, order_id)
        return order
